package com.example.social.screen

import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.social.navigation.Routes
import com.example.social.viewmodel.AuthViewModel

@Composable
fun Login(navController: NavHostController) {

    //@Compose Data
    var email by remember {
        mutableStateOf("")
    }
    var password by remember {
        mutableStateOf("")
    }

    val authViewModel: AuthViewModel = viewModel()

    val isErrorShown by authViewModel.isErrorShown.observeAsState(false)

    val resultCode by authViewModel.registerState.observeAsState(null)
    val error by authViewModel.error.observeAsState()

    val context = LocalContext.current

    //监听状态
    LaunchedEffect(resultCode, isErrorShown, error) {
        if (!isErrorShown && error != null) {
            if (resultCode == 0) {
                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                navController.navigate(Routes.BottomNav.routes) {
                    popUpTo(navController.graph.startDestinationId)
                    launchSingleTop = true
                }
            } else {
                // 显示错误消息
                val errorMessage = error!!.ifBlank { "登录失败，请重试" }
                Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
            }
            authViewModel.markErrorAsShown() // 标记错误信息已经显示
        }
    }



    //@Compose UI
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally, //水平居中
        verticalArrangement = Arrangement.Center  //垂直居中
    ) {

        Text(
            text = "Login",
            style = TextStyle(
                fontWeight = FontWeight.ExtraBold,
                fontSize = 24.sp
            )
        )

        Box(modifier = Modifier.height(50.dp))
        //邮箱
        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = {
                Text(text = "邮箱")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Email // 点击输入框时自动弹出专门用于电子邮件输入的键盘
            ),
            singleLine = true,//支持单行输入，不会自动换行
            modifier = Modifier.fillMaxWidth()
        )
        Box(modifier = Modifier.height(20.dp))
        //密码
        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = {
                Text(text = "密码")
            }, keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password // 点击输入框时自动弹出专门用于密码输入的键盘
            ),
            singleLine = true,
            modifier = Modifier.fillMaxWidth()
        )
        Box(modifier = Modifier.height(30.dp))
        //登录
        ElevatedButton(
            onClick = {
                if(email.isEmpty()||password.isEmpty()){
                    Toast.makeText(context,"请填写正确的邮箱或密码!",Toast.LENGTH_SHORT).show()
                }else{
                    authViewModel.login(email,password,context)
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "登录",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = 24.sp
                ),
                modifier = Modifier.padding(vertical = 6.dp) //垂直方向的内边距 6.dp
            )
        }
        //去注册
        TextButton(
            onClick = {
                navController.navigate(Routes.Register.routes){
                    popUpTo(navController.graph.startDestinationId)
                    launchSingleTop = true
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "新用户? 去注册",
                style = TextStyle(
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp
                )
            )
        }
    }
}

@Composable
@Preview(showBackground = true)
fun LoginPreview() {
    val navController  = rememberNavController()
    Login(navController)
}
